package com.whereareyou.servlet;

import com.google.gson.Gson;
import com.google.inject.Provider;
import com.whereareyou.Util;
import com.whereareyou.model.Position;
import com.whereareyou.model.User;
import com.whereareyou.service.PositionService;
import com.whereareyou.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * Created by 家玮 on 2014/7/25.
 */
@Singleton
public class PositionServlet extends HttpServlet{
    final static Logger log = LoggerFactory.getLogger(PositionServlet.class);
    private final UserService userService;
    private final PositionService positionService;

    @Inject
    public PositionServlet(Provider<UserService> userServiceProvider, Provider<PositionService> positionServiceProvider) {
        this.positionService = positionServiceProvider.get();
        this.userService = userServiceProvider.get();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug(req.getPathInfo());
        log.debug(req.getPathTranslated());
        log.debug(req.getRequestURI());
        log.debug(req.getServletPath());
        log.debug(userService.getCurrentUser().getNickname());
        String userId = req.getParameter("userId");
        Position position = positionService.getPoiIn5Minute(userId);
        if(position!=null) {
            Gson gson = new Gson();
            resp.setContentType("application/json;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().print(gson.toJson(position));
            resp.getWriter().flush();
            resp.getWriter().close();
        }else {
            resp.setStatus(404);
            req.getRequestDispatcher("/notFound.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.debug(req.getParameter("lat"));
        log.debug(req.getParameter("lng"));
        User currentUser = userService.getCurrentUser();
        Double lat = Double.parseDouble(req.getParameter("lat"));
        Double lng = Double.parseDouble(req.getParameter("lng"));
        Util.save(()->{
            Position position = new Position();
            position.setDateCreated(new Date());
            position.setLat(lat);
            position.setLng(lng);
            position.setUser(currentUser);
            return position;
        });
        log.debug("hahahahah");
    }
}
